package com.cheung.shopkeeper.common.mail;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;

import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;
import java.util.List;


public class MailUtil {
	/**
	 * logger
	 */
	private static final Log logger = LogFactory.getLog(MailUtil.class);

	/**
	 * 邮件发送的方法
	 * 
	 * @param message
	 *            将要发送的消息
	 */
	public void sendMail(final MailMessage message) {
		logger.info("[MailSendHelper.sendMail] - sendMail all begin");
		logger.info("[MailSendHelper.sendMail] - messageSubject:" + message.getSubject());
		
		/*
		 * spring的JavaMail实现
		 */
		JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();

		// 设置Host
		javaMailSenderImpl.setHost(smtpServerName);

		javaMailSenderImpl.send(new MimeMessagePreparator() {

			public void prepare(MimeMessage mimeMessage) {

				try {
					MimeMessageHelper messageHelper = new MimeMessageHelper(
							mimeMessage, true, "UTF-8");

					messageHelper.setTo(message.getReceivers());// 接收者
					if(message.getCopys() != null) messageHelper.setCc(message.getCopys());//抄送着
					if(null == message.getSubject()) message.setSubject("无主题");
					messageHelper.setSubject(message.getSubject());// 主题
					if(null == message.getIsHtml())message.setIsHtml(false);
					messageHelper.setText(message.getContent(),message.getIsHtml());// 内容
					if(message.getSendTime()!=null)messageHelper.setSentDate(message.getSendTime());// 发送时间
					else messageHelper.setSentDate(new Date(System.currentTimeMillis()));// 发送时间
		
					List<File> attachments = message.getAttachements();// 获取文件类型的附件

					List<String> attachmentNames = message.getAttachmentNames();// 获取附件名称
					List<DataSource> dataSourceAttachs = message
							.getDataSourceAttachs();// 获取数据源类型的附件

					// 如果文件类型的附件不为空就发文件类型附件，否者发数据源类型的附件
					if (attachments != null && !attachments.isEmpty()) {
						for (File file : attachments) {
							logger.info("[MailSendHelper.sendMail] - attachmentName" 
									+ (attachments.indexOf(file) + 1) + ": "+ file.getName());
							messageHelper.addAttachment(file.getName(), file);
						}
					} else if (dataSourceAttachs != null && !dataSourceAttachs.isEmpty()) {
						String prefix = "attachment";
						String suffix = ".xls";
						String fileName = prefix + suffix;
						for (int i = 0; i < dataSourceAttachs.size(); i++) {
							/*
							 * TODO 数据源的类型匹配有待改进，现在只用这几种格式,根据mimeType才知道文件的后缀
							 */
							String mimeType = dataSourceAttachs.get(i).getContentType();
							if (mimeType.equals("application/msword")) {
								suffix = ".docx";
							} else if (mimeType
									.equals("application/vnd.ms-excel")) {
								suffix = ".xls";
							} else if (mimeType
									.equals("application/vnd.ms-powerpoint")) {
								suffix = ".pptx";
							} else if (mimeType.equals("application/pdf")) {
								suffix = ".pdf";
							} else if (mimeType.equals("application/zip")) {
								suffix = ".zip";
							} else {
								suffix = ".txt";
							}
							if (attachmentNames != null && !attachmentNames.isEmpty()) {
								String tempName = fileName;
								if (attachmentNames.get(i).endsWith(suffix)) {
									tempName = attachmentNames.get(i);
								} else {
									tempName = attachmentNames.get(i) + suffix;
								}
								fileName = tempName;
							} else {
								fileName = "attachment-" + (i + 1) + suffix;
							}
							logger.info("[MailSendHelper.sendMail] - attachmentName" + (i + 1) + ": " + fileName);
							messageHelper.addAttachment(fileName,
									dataSourceAttachs.get(i));
						}
					}
				} catch (MessagingException e) {
					logger.error("[MailSendHelper.sendMail] error", e);
				}

			}

		});
		logger.info("[MailSendHelper.sendMail] - sendMail all finish");
	}
	
	private String smtpServerName;

	public String getSmtpServerName() {
		return smtpServerName;
	}

	public void setSmtpServerName(String smtpServerName) {
		this.smtpServerName = smtpServerName;
	}
}
